package concurrent.countDownLatch;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Random;
import java.util.concurrent.CountDownLatch;

/**
 * Author: Jason Wu
 * Date  : 2013-11-11
 */
public class Work implements Runnable {
    private String playerName;
    private int distance;
    private CountDownLatch beginSignal;
    private CountDownLatch endSignal;

    public Work(String playerName, int distance, CountDownLatch beginSignal, CountDownLatch endSignal) {
        this.playerName = playerName;
        this.distance = distance;
        this.beginSignal = beginSignal;
        this.endSignal = endSignal;
    }

    @Override
    public void run() {
        try {
            beginSignal.await();
            float speed = getSpeed();
            Thread.sleep(1000);
            System.out.println(String.format("%s speed : %f", playerName, speed));
            long spendTime = new BigDecimal(distance / speed).longValue();
            Thread.sleep(spendTime);
            System.out.println(String.format("%s spend :%d s !!", playerName, spendTime));
            endSignal.countDown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static float getSpeed() {
        Random random = new Random();
        return new BigDecimal(random.nextFloat() * 10).setScale(2, RoundingMode.HALF_UP).floatValue();
    }
}
